package com.zhaoyu.seata.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 代理数据源配置
 */
@Configuration
@EnableConfigurationProperties({MybatisPlusProperties.class})
public class DataSourcesProxyConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() { // 可以使用@ConfigurationProperties注解获取配置文件的值
        return new DruidDataSource();
    }

    // 创建代理数据源
    @Primary // @Primary标识必须配置在代码数据源上,否则本地事务失效
    @Bean
    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }

    private MybatisPlusProperties properties;

    public DataSourcesProxyConfig(MybatisPlusProperties properties) {
        this.properties = properties;
    }

    // 替换SqlSessionFactory的DataSource
    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSourceProxy dataSourceProxy, PaginationInterceptor paginationInterceptor) throws Exception {
        // 这里必须用 MybatisSqlSessionFactoryBean 代替了 SqlSessionFactoryBean,否则 MyBatisPlus 不会生效
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); // 创建SqlSessionFactoryBean
        mybatisSqlSessionFactoryBean.setDataSource(dataSourceProxy); // 替换数据源
        mybatisSqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory()); // 设置事务管理器
        mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() // 设置mapper文件路径
                .getResources("classpath*:/mapper/*.xml"));
        MybatisConfiguration configuration = this.properties.getConfiguration(); // 获取mybatis配置
        if(configuration == null){ // 如果没有配置,则创建一个默认配置
            configuration = new MybatisConfiguration(); // 创建默认配置
        }
        mybatisSqlSessionFactoryBean.setConfiguration(configuration); // 设置配置
        // 设置分页
        Interceptor[] plugins = {paginationInterceptor};
        mybatisSqlSessionFactoryBean.setPlugins(plugins);
        return mybatisSqlSessionFactoryBean; // 返回SqlSessionFactoryBean
    }

}